#include "Average.h"
#include <stdlib.h>

Average* newAverageWithSampleSize(int samples) {
	Average* average;
	average = (Average*) malloc(sizeof(Average));
	average->init(samples);
	return average;
}

void Average::init(int _samples) {
	samples = _samples;
	average = 0;
	count = 0;
	currentSum = 0;
	lastSum = -1;
}

int Average::averageWithValue(int value) {
	addValue(value);
	return average;
}

void Average::addValue(int value) {
	if (value < min) {
		min = value;
	} else if (value > max) {
		max = value;
	}

	currentSum += value;
	count++;

	if (count == samples) {
		lastSum = currentSum;
		currentSum = 0;
		count = 0;
	}
	
	if (count == 0) {
		average = value;
	} else if (lastSum < 0) {
		// first average calculation, don't have a lastSum yet
		average = currentSum / count;
	} else {
		average = (currentSum + lastSum) / (count + samples);
	}
}
